package pri.damai.xiaowu.usercenter.sysuser.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import pri.damai.xiaowu.common.core.enums.ResultCommonEnum;
import pri.damai.xiaowu.common.core.exception.GlobalException;
import pri.damai.xiaowu.usercenter.sysauth.service.impl.SysRoleServiceImpl;
import pri.damai.xiaowu.usercenter.sysuser.service.SysUserService;
import pri.damai.xiaowu.usercenter.sysuser.repository.SysUserDao;
import pri.damai.xiaowu.usercenter.sysuser.entity.SysUser;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 中心账户表(SysUser)表服务实现类
 * @Desc
 * @Author DaMai
 * @Date 2022-03-03 17:00:32
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUser> implements SysUserService {

    @Resource
    BCryptPasswordEncoder bCryptPasswordEncoder;
    @Resource
    SysRoleServiceImpl roleService;

    @Override
    public void saveUser(SysUser user) {

        String password = user.getPassword();
        String encodePassword = bCryptPasswordEncoder.encode(password);
        user.setPassword(encodePassword);

        if (Objects.nonNull(user.getId())) {
            user.setPassword(null);
        }

        save(user);
    }

    @Override
    public SysUser getUserByPhone(String phone) {
        LambdaQueryWrapper<SysUser> wrapper = getLambda().eq(SysUser::getPhone, phone);

        SysUser sysUser = this.getOne(wrapper);

        if (Objects.isNull(sysUser)) {
            throw new GlobalException(ResultCommonEnum.AUTHORIZED_FAIL.code(),"用户不存在。");
        }
        return sysUser;
    }

    public LambdaQueryWrapper<SysUser> getLambda() {
        return new LambdaQueryWrapper<>();
    }
}
